import {
    DatePicker,
    FormItemProps,
    FormProps,
    Input,
    InputNumber,
    InputPassword,
    AutoComplete,
    CheckboxGroup,
    Cascader,
    RangePicker,
    Select, Mentions, RadioGroup, Rate, Slider, Switch, TimePicker, TreeSelect, Upload
} from "ant-design-vue";

interface FormItemMapType {
    [key: string]: { component: any, placeholderPrefix?: string; },
}

const formItemMap: FormItemMapType = {
    "auto-complete": {
        component: AutoComplete,
        placeholderPrefix: "请输入",
    },
    "cascader": {
        component: Cascader,
        placeholderPrefix: "请选择",
    },
    "checkbox-group": {
        component: CheckboxGroup,
    },
    "date": {
        component: DatePicker,
    },
    "input": {
        component: Input,
        placeholderPrefix: "请输入",
    },
    "input-number": {
        component: InputNumber,
        placeholderPrefix: "请输入",
    },
    "input-password": {
        component: InputPassword,
        placeholderPrefix: "请输入",
    },
    "mentions": {
        component: Mentions,
        placeholderPrefix: "请输入",
    },
    "radio-group": {
        component: RadioGroup,
    },
    "rate": {
        component: Rate,
    },
    "select": {
        component: Select,
        placeholderPrefix: "请选择",
    },
    "slider": {
        component: Slider,
    },
    "switch": {
        component: Switch,
    },
    "time-picker": {
        component: TimePicker,
    },
    "tree-select": {
        component: TreeSelect,
    },
    "upload": {
        component: Upload,
    },
}
const queryFormItemMap: FormItemMapType = {
    ...formItemMap,
    "date": {
        component: RangePicker,
    },
}

function hasFormItemKey(key?: string): boolean {
    return key !== undefined && Object.keys(formItemMap).indexOf(key) !== -1;
}

export function getPlaceholder(item: JFormItem) {
    if (item.props?.placeholder) {
        return item.props?.placeholder
    }
    if (hasFormItemKey(item.type)) {
        const prefix = formItemMap[item.type!!].placeholderPrefix
        return prefix === undefined ? undefined : `${prefix}${item.label || item.title}`
    }
    // 返回 undefined 组件可以用默认值
    return undefined;
}

export function getComponent(type?: string, isQuery: boolean = false) {
    if (!hasFormItemKey(type)) {
        return formItemMap['input'].component
    }
    if (isQuery) {
        return queryFormItemMap[type!!].component;
    }
    return formItemMap[type!!].component;
}

export type JFormItemType = keyof typeof formItemMap

export interface JFormProps extends FormProps {
    items: JFormItem[]
    api?: string;
    colNum: number;
    showSubmit?: boolean;
    submitText?: string;
}

export interface JQueryFormProps extends JFormProps {
    loading?: boolean;
}

export interface JFormItem extends FormItemProps {
    // 兼容 table 的配置
    title?: string;
    dataIndex?: string;
    // 表单组件配置
    type?: string;
    props?: any;
}

